package cn.mengfly.product.hysitrix;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixThreadPoolKey;

/**
 * @author Mengfly
 * @date 2021/3/13 16:19
 */
public class CommandWithFallbackViaNetwork extends HystrixCommand<String> {

    private final int id;

    protected CommandWithFallbackViaNetwork(int id) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceX"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueCommand")));
        this.id = id;
    }

    @Override
    protected String run() throws Exception {
        throw new RuntimeException("force failure for example");
    }

    @Override
    protected String getFallback() {
        // 对于Fallback需要远程调用的Command
        return new FallbackViaNetwork(id).execute();
    }

    private static class FallbackViaNetwork extends HystrixCommand<String> {
        private final Integer id;

        public FallbackViaNetwork(int id) {
            super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceX"))
                    .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueFallbackCommand"))
                    // 使用不同的threadPool来执行fallbackCommand
                    .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("RemoteServiceXFallback")));
            this.id = id;
        }

        @Override
        protected String run() throws Exception {
            // 获取缓存中的值
//            return MemCacheClient.getValue(id);
            return null;
        }

        protected String getFall() {
            // 如果再次失败，采用静默降级，返回一个空值
            return null;
        }


    }
}
